﻿namespace Example
{
    using System;
    using System.Linq;
    using System.Windows.Forms;
    using Example.Properties;
    using NorthwindMapping;

    public partial class EmployeeForm : Form
    {
        private readonly Northwind _northwind;

        public EmployeeForm()
        {
            InitializeComponent();
            _northwind = new Northwind(Settings.Default.Northwind);
            var employees = from employee in _northwind.Employees
                            orderby employee.LastName
                            select employee;
            var managers = from manager in _northwind.Employees
                           orderby manager.LastName
                           select manager;

            // ToBindingList method converts query into a structure that supports IBindingList.
            // The Table<T> is required to convert to a binding list so that the addition and deletion of entities are tracked correctly.
            employeeBindingSource.DataSource = employees;
            managerBindingSource.DataSource = managers.ToList();
        }

        private static void LaunchEmployeeManager_Click(object sender, EventArgs e)
        {
            new EmployeeManagerGrids
            {
                Visible = true
            };
        }

        private void EmployeeDataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
        {
            // OfType is needed because the employeeBindingSource returns instances of type object.
            var employees = from employee in managerBindingSource.OfType<Employee>()
                            where employee.ToString() == e.Value as string
                            select employee;

            e.Value = employees.FirstOrDefault();
            e.ParsingApplied = true;
        }

        private void SubmitChanges_Click(object sender, EventArgs e)
        {
            Validate();
            _northwind.SubmitChanges();
        }
    }
}